import json
import re

from django.conf import settings
from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render
from django_redis import get_redis_connection
from itsdangerous import TimedJSONWebSignatureSerializer
import logging

from users.models import User

logger = logging.getLogger('django')
from django.views import View
from QQLoginTool.QQtool import OAuthQQ

from oauth.models import OAuthQQUser

#从项目页面跳转到QQ登录页面
class QQFirstView(View):
    #提供QQ登录页面网址
    def get(self,request):
        # next 表示从哪个页面进入到的登录页面
        # 将来登录成功后，就自动回到那个页面
        next = request.GET.get('next')
        """ 获取 QQ 登录页面网址"""
        # 创建 OAuthQQ 类的对象
        oauth =OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                       client_secret=settings.QQ_CLIENT_SECRET,
                       redirect_uri=settings.QQ_REDIRECT_URI,
                       state=next)
        #获取qq地址
        login_url = oauth.get_qq_url()

        #返回登录地址
        return JsonResponse({'code':0,
                             'errmsg':'ok',
                             'login_url':login_url})



def generate_access_token(openid):
    #功能：加密openid
    #参数：openid
    #返回token值
    serializer = TimedJSONWebSignatureSerializer(
        secret_key=settings.SECRET_KEY,
        expires_in=3600
    )

    #加密的数据是一个字典
    data = {'openid':openid}

    access_token = serializer.dumps(data)

    return access_token.decode()


def check_access_token(access_token):
    # 功能：解密出openid
    # 参数：token值
    # 返回值，返回openid
    serializer = TimedJSONWebSignatureSerializer(
        secret_key=settings.SECRET_KEY
    )
    data = serializer.loads(access_token)

    openid = data.get('openid')

    return openid

class QQUserView(View):
    #提取查询字符串参数code
    def get(self,request):
        #验证code获取token
        try:
            code=request.GET.get('code')
            oauth_qq =OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI
            )
            token = oauth_qq.get_access_token(code)
            #根据token获取openid
            openid=oauth_qq.get_open_id(access_token=token)
        # 如果上面获取 openid 出错, 则验证失败
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,
                                 'errmsg':'qq登录失败'})
    #
        try:
            oauth_qq = OAuthQQUser.objects.get(openid=openid)
            # 用户已经绑定qq,登录成功！
            user = oauth_qq.user
            login(request, user)
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
            return response
        except OAuthQQUser.DoesNotExist as e:
            #用户没有绑定过qq:我们需要返回加密的openid
            access_token = generate_access_token(openid)
            print(access_token,'2')
            return JsonResponse({
                'access_token':access_token
            })

    def post(self,request):
        #无论客户有无创建美多商城账号，都返回绑定页面
        # 根据用户传递来的手机号，判断用户是否注册美多商城账号
        user_info =json.loads(request.body.decode())
        mobile =user_info.get('mobile')
        password = user_info.get('password')
        sms_code = user_info.get('sms_code')
        access_token = user_info.get('access_token')

        if not all([mobile,password,sms_code,access_token]):
            return JsonResponse({'code':400,'errmsg':'缺少参数'})

        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '请输入正确的手机号码'})

        conn = get_redis_connection('sms_code')
        sms_code_redis =conn.get('sms_code%s'%mobile)

        if not sms_code_redis:
            return JsonResponse({'code': 400, 'errmsg': '验证码过期'})
        if sms_code_redis.decode() != sms_code:
            return JsonResponse({'code': 400, 'errmsg': '您输入的短信验证码有误！'})

        # 把openid从access_token参数中解密出来
        openid = check_access_token(access_token)


        try:
            user = User.objects.get(mobile=mobile)

        except Exception as e:
            #没有注册，新建再绑定
            user =User.objects.create(
                username=mobile,
                mobile=mobile,
                password=password
            )
            #绑定openid
            OAuthQQUser.objects.create(openid=openid,user=user)
            login(request,user)
            response=JsonResponse({'code':0,'errmsg':'ok'})
            response.set_cookie('username',user.username,max_age=3600*24*14)
            return response

        # 已经注册，直接绑定
        OAuthQQUser.objects.create(openid=openid, user=user)
        login(request, user)
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return response

